import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    // 首页
    path: '/',
    component: Home
  },
  {
    // 购物车
    path: '/cart',
    component: () => import('../views/Cart.vue')
  },
  {
    // 我的
    path: '/mine',
    component: () => import('../views/mine/Mine.vue')
  },
  {
    // 登录
    path: '/login',
    component: () => import('../views/Login.vue')
  },
  {
  // 商品详情
    path: '/goodsDetail/:id',
    component: () => import('../views/GoodsDetail.vue'),
    meta: { requireAuth: true }
  },
  {
    // 我的地址
    path: '/mine/myAddress',
    component: () => import('../views/mine/children/MyAddress.vue'),
    meta: {
      requireAuth: true
    }
  },
  {
    // 添加地址
    path: '/mine/myAddress/addAddress',
    component: () => import('../views/mine/children/AddAddress.vue'),
    meta: {
      requireAuth: true
    }
  },
  {
    // 用户中心
    path: '/mine/userCenter',
    component: () => import('../views/mine/children/UserCenter.vue'),
    meta: {
      requireAuth: true
    }
  },
  {
    // 填写订单
    path: '/account',
    component: () => import('../views/Account.vue'),
    meta: {
      requireAuth: true
    }
  },
  {
    // 我的订单
    path: '/mine/myOrder',
    component: () => import('../views/mine/children/MyOrder.vue'),
    meta: {
      requireAuth: true
    }
  },
  {
    // 语言
    path: '/switchLanguage',
    component: () => import('../views/mine/children/SwitchLanguage.vue')
  }
]

const router = new VueRouter({
  mode: 'hash', // history  &  hash
  base: process.env.BASE_URL,
  routes,
  scrollBehavior (to, from, savedPosition) {
    return { x: 0, y: 0 }
  }
})

// 路由导航守卫
router.beforeEach((to, form, next) => {
  // 根据meta里判断有没有requireAuth属性
  if (to.meta !== undefined && to.meta.requireAuth !== undefined && to.meta.requireAuth) {
    // 判断有没有token
    let token = localStorage.getItem('token')
    // 如果没token 就去登录页
    if (!token) {
      // Toast('请先登录')
      return next('/login')
    }
  }
  // 跳转页面置顶
  document.body.scrollTop = 0
  // 否则放行
  next()
})

export default router
